home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / snip1292.zip / MEMREV.C < prev    next >
C/C++ Source or Header  |  1992-12-26  |  1KB  |  51 lines

  1. /*
  2. **  Public domain demo by Ray Gardner, 7 dec 88
  3. **
  4. **  Here's an old programming trick that (I bet) will be new to at least a
  5. **  few of you out there, even some "old hands".  I don't remember where I
  6. **  saw this; it might have been Jon Bentley's "Programming Pearls" column in
  7. **  Communications of the ACM.
  8. **
  9. **  Have you ever wanted to exchange two adjacent areas of storage which
  10. **  might be of two different lengths?  There are some tricky and complicated
  11. **  "efficient" methods to do this without using a lot of extra temporary
  12. **  storage.  But there is also an old and simple way: Assume that the buffer
  13. **  looks like this:
  14. **
  15. **     |...... head .......|.................. tail .................|
  16. **
  17. **  You reverse the head, reverse the tail, then reverse the entire buffer.
  18. **  That's all there is to it.  It will leave you with:
  19. **
  20. **     |.................. tail .................|...... head .......|
  21. **
  22. **  Here's code:
  23. */
  24.  
  25. /*
  26. **  reverse "count" bytes starting at "buf"
  27. */
  28.  
  29. void memrev(char  *buf, size_t count)
  30. {
  31.       char *r;
  32.  
  33.       for (r = buf + count - 1; buf < r; buf++, r--)
  34.       {
  35.             *buf ^= *r;
  36.             *r   ^= *buf;
  37.             *buf ^= *r;
  38.       }
  39. }
  40.  
  41. /*
  42. **  swap "head" bytes with "tail" bytes at "buf"
  43. */
  44.  
  45. void aswap(char  *buf, size_t head, size_t tail)
  46. {
  47.       memrev(buf, head);
  48.       memrev(buf + head, tail);
  49.       memrev(buf, head + tail);
  50. }
  51.